package com.ncs.nc.mq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class MqRabbitConsumer {

    //消费者要监听的队列名称
    private static final String QUEUE="mq.simple.queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接
        Connection con=MqRabbitConnectionUtil.getConnection();
        //创建信道
        Channel channel=con.createChannel();

        //消费者
        Consumer consumer=new DefaultConsumer(channel){
            //消费者监听消费消息时执行的代码块
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //去除消息体中的信息
                String message=new String(body);
                //监听到的消息内容
                System.out.println("消费者监听到的消息内容:"+message);
                //确认消费
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };

        //消费消息
        channel.basicConsume(QUEUE,false,consumer);
    }
}
